package com.gcpproxy.api;
import com.gcpproxy.image.ImageHandler;
import com.google.common.collect.ImmutableList;
import com.google.genai.Client;
import com.google.genai.types.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Gemini API客户端
 * 封装与Google Gen AI API的交互
 */
@Component
public class GeminiApiClient {

    private static final Logger logger = LoggerFactory.getLogger(GeminiApiClient.class);
    
    @Autowired
    private ImageHandler imageHandler;
    
    private Client genaiClient;
    private final Object clientLock = new Object();


    private List< SafetySetting > defaultSafety() {
        List<  SafetySetting > sf = new ArrayList<>();
        sf.add( safetySetting( "HARM_CATEGORY_HARASSMENT" ,"BLOCK_NONE"  ) );//骚扰、霸凌内容（如辱骂、人身攻击）
        sf.add( safetySetting( "HARM_CATEGORY_HATE_SPEECH" ,"BLOCK_MEDIUM_AND_ABOVE"  ) );// 仇恨言论（如基于种族、宗教、性别的歧视言论） 拦截中及以上风险，默认
        sf.add( safetySetting( "HARM_CATEGORY_SEXUALLY_EXPLICIT" ,"BLOCK_NONE"  ) );//色情、露骨内容
        sf.add( safetySetting( "HARM_CATEGORY_DANGEROUS_CONTENT" ,"BLOCK_ONLY_HIGH"  ) );//危险内容（如暴力教程、毒品制作、自残引导）
        sf.add( safetySetting( "HARM_CATEGORY_UNSPECIFIED" ,"BLOCK_ONLY_HIGH"  ) );//未指定类型
        return sf;
    }
    /**
     * 懒初始化 GenAI Client
     */
    private Client getGenaiClient() {
        if (genaiClient == null) {
            synchronized (clientLock) {
                if( genaiClient == null) {
                    genaiClient = Client.builder().vertexAI( true ).build();
                    logger.info( "google-genai Client 已初始化（Vertex AI / ADC）" );
                }
            }
        }
        return genaiClient;
    }

    /**
     * 生成内容
     */
    public GenerateContentResponse generateContent(
            String model, String textPrompt,
            List<String> images, List<String> responseModalities,
            double temperature, int maxOutputTokens) {

        logger.info("开始调用Gemini API生成内容 - 模型: {}, 文本长度: {}, 图片数量: {}",  model,
                textPrompt != null ? textPrompt.length() : 0,
                images != null ? images.size() : 0);

        // 构建内容部分（parts）- 使用新的 API
        List<Part> parts = new ArrayList<>();
        
        // 添加文本部分
        if (textPrompt != null && !textPrompt.trim().isEmpty()) {
            parts.add(Part.fromText(textPrompt.trim()));
        }
        
        // 添加图片部分
        if (images != null && !images.isEmpty()) {
            for (String imageUrl : images) {
                Map<String, Object> processedImage = imageHandler.processImage(imageUrl);
                String mimeType = (String) processedImage.get("mimeType");
                byte[] bytes = (byte[]) processedImage.get("data");
                Blob blob = Blob.builder()
                    .data( bytes)
                    .mimeType( mimeType )
                    //.displayName(  )
                    .build();
                Part image = Part.builder().inlineData(  blob ).build();
                parts.add(image);
                logger.info("成功添加图片到请求 - MIME类型: {}", mimeType);
            }
        }
        
        // 如果没有内容，返回错误
        if (parts.isEmpty()) {
            throw new IllegalArgumentException("请求必须包含文本或图片内容");
        }

        // 构建 Content 对象 - 使用新的 API
        Content content = Content.builder()
                .role("user")
                .parts(ImmutableList.copyOf(parts))
                .build();
        
        // 定义配置
        GenerateContentConfig.Builder configBuilder = GenerateContentConfig.builder()
            .temperature((float) temperature)
            .safetySettings( defaultSafety() )
            .candidateCount(1);
        
        // 对于非图片生成模型，设置 response_mime_type
        if (model == null || !model.contains("image")) {
            configBuilder.responseMimeType("application/json");
        }
        
        // 只在图片生成模型上设置 responseModalities（某些模型不支持多模态输出）
        if (model != null && model.contains("image") && responseModalities != null && !responseModalities.isEmpty()) {
            configBuilder.responseModalities(responseModalities);
        }
        
        if (maxOutputTokens > 0) {
            configBuilder.maxOutputTokens(maxOutputTokens);
        }
        
        GenerateContentConfig config = configBuilder.build();
        Client client = getGenaiClient();
        try {
            // 调用 Gemini API
            GenerateContentResponse response = client.models.generateContent(
                    model ,
                    ImmutableList.of( content ) ,
                    config
            );
            logger.info( response.text().replaceAll( "\\n\\s*" ,"") );
            return response;
        }finally {
            client.close();
        }
    }

    private SafetySetting safetySetting( String category , String threshold ) {
        return SafetySetting.builder()
           .category( category )
           .threshold(threshold )
           .build();
    }


}